<template>
  <a-modal
    title="操作"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="商圈">
          <a-select
            v-decorator="[ 'companyId', {rules: [{ required: true, message: '请选择商圈' }],initialValue: defaultCompany}]"
            placeholder="请选择商圈">
            <a-select-option :value="company.id" v-for="company in companyList" :key="company.id">
              {{company.name}}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="名称"
        >
          <a-input placeholder="名称"
                   v-decorator="[ 'name', {rules: [{ required: true, message: '请输入。。。' }]} ]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="跳转路径"
        >
          <a-input placeholder="跳转路径" v-decorator="[ 'transUrl', {rules: [{ required: true, message: '请输入。。。' }] }]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="图片"
        >
          <a-upload
            :action="this.$baseURL+'/common/upload/uploadImg'"
            listType="picture-card"
            :fileList="fileList"
            @preview="uploadPreviewBack"
            @change="uploadChange"
            :beforeUpload="beforeUpload"
            :data="ruleForm"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus"/>
              <div class="ant-upload-text">上传背景图</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="uploadCancel">
            <img alt="example" style="width: 100%" :src="previewImage"/>
          </a-modal>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="顺序"
        >
          <a-input placeholder="顺序" v-decorator="[ 'configOrder', {rules: [{ required: true, message: '请输入。。。' }] }]"/>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { save,selectConfigByCompanyId } from '@/api/system/config'
  import { selectAll } from '@/api/merchantService/merchant'
  import pick from 'lodash.pick'

  export default {
    //--############  data() ###############-->
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },

        ruleForm: {
          height: 690,
          width: 340
        },
        visible: false,
        confirmLoading: false,
        mdl: {},
        form: this.$form.createForm(this),
        previewVisible: false,
        isDisabled: false,
        roles: [],
        fileList: [],
        iconUrl :'',
        previewImage:[],
        companyList:[],
        defaultCompany:'',
        company:{}
      }
    },
    //--############  data() ###############-->

    created() {
      selectAll().then(res => {
        this.companyList = res.result
        this.defaultCompany = this.companyList[0].id
        this.company = {
          'companyId': this.defaultCompany
        }

      })
    },

    //--############  methods() ###############-->
    methods: {
      add() {
        this.isDisabled = false
        this.visible = true
      },
      edit(record) {
        this.isDisabled = true
        this.mdl = Object.assign({}, record)
        this.visible = true
        if(record){
          this.fileList = [{ 'uid': '123', 'url': record.iconUrl.toString(), 'name': '123' }]
        }

        selectConfigByCompanyId(record.id).then(res => {
          this.mdl.roleIds = res.result
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.mdl, 'companyId','name', 'transUrl',  'configOrder'))
          })
        })

      },
      close() {
        this.$emit('close')
        this.visible = false
        this.form.resetFields()
        this.mdl={}
      },
      uploadCancel() {
        this.previewVisible = false
      },
      uploadPreviewBack(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      uploadChange(info) {
        const _this = this
        _this.fileList = info.fileList
        if (info.file.status === 'done') {
          _this.fileList.pop()
          _this.fileList.push(info.file)
          _this.iconUrl  = info.file.response.url
          this.$message.success(`${info.file.name} 上传成功`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (info.file.status === 'removed') {
          // deletePic(info.file.uid).then(res => {
          // })
        }
      },
      beforeUpload(file){
        const sizeOk = file.size <1024 * 500;
        const isJPEG = file.type === 'image/jpeg'
        const isJPG = file.type === 'image/jpg'
        const isPNG = file.type === 'image/png'
        // if (!isJPG && !isJPEG && !isPNG) {
        //   this.$message.error('只支持文件格式jpg,png')
        // }
        // if(!sizeOk){
        //   this.$message.error('照片大小超过500K！');
        // }
        // return sizeOk && file.type

        return new Promise((resolve, reject) => {
          if(!isJPG && !isJPEG && !isPNG) {
            this.$message.error('只支持文件格式jpg,png')
            reject(file);
          } else if(!sizeOk) {
            this.$message.error('照片大小超过500K！');
            reject(file);
          }else {
            resolve(file);
          }
        });
      },
      handleOk() {
        const _this = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            values.id = this.mdl.id;
            _this.confirmLoading = true
            values.iconUrl  = _this.iconUrl
            // 模拟后端请求 2000 毫秒延迟
            save(values).then((res) => {
              if (res.code === 200) {
                _this.$message.success('保存成功')
                _this.$emit('ok')
                _this.close()
              }else {
                this.$notification.error({
                  message: '错误',
                  description: res.message,
                  duration: 4
                })
              }
            }).catch(() => {
              // Do something
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        })
      },
      handleCancel() {
        this.close()
      },
    }
    //--############  methods() ###############-->
  }
</script>

<style scoped>

</style>
